package cz.zcu.fav.rat.managed.validator;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import cz.zcu.fav.rat.dataaccess.service.ObjectService;
import cz.zcu.fav.rat.managed.bean.SpringBeanFactory;
import cz.zcu.fav.rat.managed.locale.LocaleMessageFactory;

@FacesValidator(value = "createObjectValidator")
public class CreateObjectValidator implements Validator
{

	@Override
	public void validate(FacesContext context, UIComponent component,
			java.lang.Object value) throws ValidatorException
	{
		UIInput identifierInput = (UIInput) component.getAttributes().get(
				"ident");
		String ident = (String) identifierInput.getSubmittedValue();

		ObjectService service = SpringBeanFactory.getInstance()
				.<ObjectService> getBean("objectService", ObjectService.class);

		List<cz.zcu.fav.rat.beans.Object> objects = service
				.findAllObjectsByIdentifier(ident);
		if (objects != null && !objects.isEmpty())
		{
			String message = LocaleMessageFactory
					.getLocale("view.objectcreate.error.duplicateidentifier");

			identifierInput.setValid(false);
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					message, null);

			throw new ValidatorException(msg);
		}
	}

}
